package com.example.java.thread;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j
@Service
public class MyAsyncService {

    private final ReentrantLock lock = new ReentrantLock();

    private final ReentrantLock lock1 = new ReentrantLock();

    @Async("myThreadPoolExecutor")
    public void asyncMethod() {
        while (true){
            log.info(Thread.currentThread().getName());
        }
    }

    @Async("myThreadPoolExecutor")
    public void deadLock() {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + " get lock");
            try {
                Thread.sleep(2000);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
            lock1.lock();
            System.out.println(Thread.currentThread().getName() + " get lock1");
        }finally {
            lock.unlock();
            lock1.unlock();
        }
    }

    @Async("myThreadPoolExecutor")
    public void deadLock1() {
        lock1.lock();
        try {
            System.out.println(Thread.currentThread().getName() + " get lock1");
            try {
                Thread.sleep(2000);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
            lock.lock();
            System.out.println(Thread.currentThread().getName() + " get lock");
        }finally {
            lock1.unlock();
            lock.unlock();
        }
    }
}
